
package com.tangcheng.redislistener.expire.job;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

//@Service
@Slf4j
public class RedisBatchSetJob {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron = "0 */1 * * * ?")
    public void initKeys() {
        LocalDateTime now = LocalDateTime.now();
        log.info("开始设置key");
        for (int i = 1; i < 10; i++) {
            /**
             * 写入redis中数据量大时，延迟更明显
             */
            int value = ThreadLocalRandom.current().nextInt();
            stringRedisTemplate.opsForValue().set("randomKey_" + value + "@" + dateTimeFormatter.format(LocalDateTime.now().plusMinutes(1)), String.valueOf(value), 1, TimeUnit.MINUTES);
        }
        log.info("设置完毕: " + Duration.between(now, LocalDateTime.now()));
    }


}